Page({
  data: {
    dialogVisible: false,
    list: [],
    isEmpty: false,
  },
  onShow() {
    this.getHouseList()
  },
  swipeClose(ev) {
    this.id = ev.mark.id
    this.cellIndex = ev.mark.cellIndex
    const { position, instance } = ev.detail
    if (position === 'right') {
      // 显示 Dialog 对话框
      this.setData({
        dialogVisible: true,
      })

      // swiper-cell 滑块关闭
      instance.close()
    }
  },

  goDetail(ev) {
    wx.navigateTo({
      url: '/house_pkg/pages/detail/index?id=' + ev.mark.id,
    })
  },

  addHouse() {
    wx.navigateTo({
      url: '/house_pkg/pages/locate/index',
    })
  },
  // 弹窗关闭时触发
  async dialogClose(ev) {
    // 查看事件源 如果是点击确定触发的话就调删除的接口 否则啥也不干
    console.log(ev.detail)
    if (ev.detail === 'confirm') {
      const { code } = await wx.http.delete('/room/' + this.id)
      console.log(code)
      if (code !== 10000) return wx.utils.toast('删除失败！')
      // 也要把data中的数据更新一下
      this.data.list.splice(this.cellIndex, 1)
      this.setData({
        list: this.data.list,
        isEmpty: this.data.list.length === 0,
      })
    }
  },
  // 获取房屋列表
  async getHouseList() {
    const { data, code } = await wx.http.get('/room')
    if (code !== 10000) return wx.utils.toast('请求房屋消息失败')
    this.setData({
      list: data,
      isEmpty: data.length === 0,
    })
  },
})
